package com.docios.cookbook2.ui.loginPager;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.PatternMatcher;
import android.preference.PreferenceManager;
import android.widget.Toast;

import com.docios.cookbook2.Dao.AppDatabase;
import com.docios.cookbook2.Dao.DatabaseImpl;
import com.docios.cookbook2.Dao.UserDao;
import com.docios.cookbook2.databinding.ActivityLoginBinding;
import com.docios.cookbook2.entity.User;
import com.docios.cookbook2.ui.homePager.HomeActivity;

import java.util.List;

public class LoginActivity extends AppCompatActivity {
    ActivityLoginBinding loginBinding;
    AppDatabase db;
    UserDao userDao;

    /*
     * 启动下一个页面，传值回本页面。
     * 启动下个页面：
     * startForResult.launch(Intent);
     * 在下个页面中，传值回上个页面：
     * public static final String KEY_NAME = "NAME";
     * Intent intent=new Intent().putExtra(KEY_NAME, Object);
     * setResult(RESULT_OK, intent);
     * */
//    ActivityResultLauncher<Intent> startForResult = registerForActivityResult(    //启动器
//            new ActivityResultContracts.StartActivityForResult(),       //输入Intent，输出Result
//            new ActivityResultCallback<ActivityResult>() {      //接收结果回调
//                @Override
//                public void onActivityResult(ActivityResult o) {
//                    if (o != null && o.getResultCode() == RESULT_OK) {
//                        if (o.getData() != null && o.getData().getStringExtra(RegisterActivity.KEY_NAME) != null) {
//                            loginBinding.inputPhone.setText(o.getData().getStringExtra(RegisterActivity.KEY_NAME));
//                        }
//                    }
//                }
//            }
//    );

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loginBinding = ActivityLoginBinding.inflate(getLayoutInflater());
        initData();//是否跳过登录
        setContentView(loginBinding.getRoot());


//        registerData();//不需要了
        btnLoginOnClick();
        btnForgotOnClick();
        btnRegisterOnclick();
    }

    private void initData() {
        //实例化数据库
        db = DatabaseImpl.setInstance(getApplicationContext());
        userDao = db.userDao();
        List<User> registered=userDao.getAllU();
        if (!registered.isEmpty()){
            Intent intent=new Intent(this, HomeActivity.class);
            intent.putExtra("phone",registered.get(0).phone);
            startActivity(intent);
            Toast.makeText(this, "欢迎回来", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void registerData() {
        //注册页面传来的值
        loginBinding.inputPhone.setText(getIntent().getStringExtra("phone"));
        loginBinding.inputPassword.setText(getIntent().getStringExtra("pwd"));
    }

    private void btnLoginOnClick() {
        loginBinding.btnLogin.setOnClickListener(view -> {
            String editPhone = loginBinding.inputPhone.getText().toString();
            String editPwd = loginBinding.inputPassword.getText().toString();


            //输入检测警告
            if (editPhone.isEmpty()) {
                loginBinding.inputPhoneLayout.setError("请输入手机号");
                return;
            } else {
                loginBinding.inputPhoneLayout.setErrorEnabled(false);
            }

            if (editPwd.isEmpty()) {
                loginBinding.inputPwdLayout.setError("请输入密码");
                return;
            } else {
                loginBinding.inputPwdLayout.setErrorEnabled(false);
            }

            //数据库校验
            List<User> userList = userDao.getAllByPhoneU(editPhone);
            if (!userList.isEmpty()) {
                //List<>.get(index) 第一个 index 为 0
                User user = userList.get(0);

                if (editPhone.equals(user.phone) && editPwd.equals(user.password)) {
                    Intent intent=new Intent(this, HomeActivity.class);
                    intent.putExtra("phone",user.phone);
                    startActivity(intent);
                    Toast.makeText(this, "登陆成功", Toast.LENGTH_SHORT).show();
                    finish();
                }
            } else {
                Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
            }

        });
    }

    private void btnForgotOnClick() {
    }

    private void btnRegisterOnclick() {
        loginBinding.btnToRegister.setOnClickListener(view -> {
            startActivity(new Intent(this, RegisterActivity.class));
            finish();
        });

    }
}